package com.samxcode.leetcode;

/**
 * Given a linked list, swap every two adjacent nodes and return its head.
 * 
 * Solution:
 * add a node before the head node to avoid testing the head node in the loop
 * @author Sam
 *
 */
public class SwapPairs {
    
    public static void main(String[] args) {
        ListNode.printListNode(swapPairs(ListNode.generateListNode(5)));
    }
    
    public static ListNode swapPairs(ListNode head) {
        ListNode first, second, node = new ListNode(0);
        node.next = head;
        head = node;
        while (node.next != null && node.next.next != null) {
            first = node.next;
            second = first.next;
            first.next = second.next;
            second.next = first;
            node.next = second;
            node = first;
        }
        return head.next;
    }
}
